//
//  GroupSetSPViewController.m
//  sentorise
//
//  Created by admin on 2025/9/12.
//

#import "GroupSetSPViewController.h"
#import "GlobalDefine.h"
#import "BTManager.h"
#import "GroupSPCollectionViewCell.h"
#import "GroupSearchBleListView.h"
#import "ProgressHUD.h"

@interface GroupSetSPViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDragDelegate, UICollectionViewDropDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topS;
@property (weak, nonatomic) IBOutlet UILabel *psLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *svWidth;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UILabel *descLabel;
@property (weak, nonatomic) IBOutlet UILabel *descLabel1;

@property (nonatomic, strong) NSMutableArray<BlutoothModel *> *orgDataArray;
@property (nonatomic, strong) NSMutableArray<BlutoothModel *> *dataArray;
@property (nonatomic, strong) NSMutableArray<NSString *> *deleteNames;

@property (nonatomic, assign) NSInteger colums;
@property (nonatomic, assign) NSInteger rows;
@property (nonatomic, assign) CGFloat collectItemW;

@end

@implementation GroupSetSPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topS.constant = IPHONE_X ? 54 : 20;
    self.titleLabel.text = NSLocalizedString(@"RV Battery", nil);
    self.descLabel.text = NSLocalizedString(@"System Configuration", nil);
    self.descLabel1.text = NSLocalizedString(@"Drag and drop to adjust battery series and parallel sequence structure", nil);
    [self.submitBtn setTitle:NSLocalizedString(@"Submit", nil) forState:UIControlStateNormal];
    
    self.orgDataArray = [[NSMutableArray alloc] init];
    self.dataArray = [[NSMutableArray alloc] init];
    self.deleteNames = [[NSMutableArray alloc] init];
    self.colums = self.model.s.integerValue;
    self.rows = self.model.p.integerValue;
    self.psLabel.text = [NSString stringWithFormat:@"%@P%@S", self.model.p, self.model.s];
    self.collectItemW = (kWidth - 40) / 2;
    if (self.colums == 1) {
        self.collectItemW = (kWidth - 40);
    }else if(self.colums > 2) {
        self.collectItemW -= 20;
    }
    self.svWidth.constant = self.collectItemW * self.colums;

    if (!self.model.bluList || !self.model.bluList.count) {
        for (NSInteger i=0; i<(self.rows * self.colums); i++) {
            [self.orgDataArray addObject:[[BlutoothModel alloc] init]];
        }
        [self.dataArray addObjectsFromArray:self.orgDataArray];
    }else {
        for (BlutoothModel *model in self.model.bluList) {
            [self.orgDataArray addObject:[BlutoothModel covertToModel:[model toJson]]];
        }
        [self.dataArray addObjectsFromArray:self.orgDataArray];
    }
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"GroupSPCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GroupSPCollectionViewCell"];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionDelete:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Confirm delete?", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler: nil]];
    WeakSelf
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (weakSelf.model.groupId) {
            NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
            NSMutableArray *array = [NSMutableArray array];
            if (groupStr.length) {
                NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
                for (BlutoothGroupModel *group in dataArray) {
                    if (![group.groupId isEqualToString:weakSelf.model.groupId]) {
                        [array addObjectsFromArray:dataArray];
                    }
                }
            }
            NSString *str = [BlutoothGroupModel toJson:array];
            [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSNotificationCenter defaultCenter] postNotificationName:kBTBluGroupChanged object:nil];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionConfirm:(id)sender {
    BOOL canSave = YES;
    for (NSInteger i=0; i<self.dataArray.count; i++) {
        BlutoothModel *blu = self.dataArray[i];
        if (!blu.name.length || !blu.uuid.length) {
            canSave = NO;
        }
    }
    if (!canSave) {
        [ProgressHUD showErrorMessage:NSLocalizedString(@"Please select device", nil)];
        return;
    }
    NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
    NSMutableArray *array = [NSMutableArray array];
    if (groupStr.length) {
        NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
        for (BlutoothGroupModel *group in dataArray) {
            if (![group.groupId isEqualToString:self.model.groupId]) {
                [array addObject:group];
            }
        }
    }
    self.model.bluList = self.dataArray;
    [array addObject:self.model];
    NSString *str = [BlutoothGroupModel toJson:array];
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:BatteryGroupBluList];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:kBTBluGroupChanged object:nil];
    if (self.isQueryIn) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (void)updateGroup:(NSArray<CBPeripheral *> *)list {
    for (NSInteger i=0; i<self.dataArray.count; i++) {
        BlutoothModel *blu = self.dataArray[i];
        if (list.count > i) {
            blu.name = list[i].name;
            blu.uuid = list[i].identifier.UUIDString;
        }else {
            blu.name = @"";
            blu.uuid = @"";
        }
    }
    [self.collectionView reloadData];
}


#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GroupSPCollectionViewCell *cell = (GroupSPCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"GroupSPCollectionViewCell" forIndexPath:indexPath];
    BOOL isFirstLine = indexPath.item < self.colums;
    BOOL isLastLine = indexPath.item >= self.colums * (self.rows - 1);
    if (self.rows == 1) {
        cell.lhView.hidden = indexPath.item == 0;
        cell.rhView.hidden = indexPath.item == self.dataArray.count - 1;
    }
    cell.ltView.hidden = isFirstLine;
    cell.rtView.hidden = isFirstLine;
    cell.lbView.hidden = isLastLine;
    cell.rbView.hidden = isLastLine;
    BlutoothModel *blu = self.dataArray[indexPath.item];
    cell.addIV.hidden = blu.uuid.length > 0;
    cell.batterIV.hidden = !cell.addIV.hidden;
    cell.nameLabel.hidden = cell.batterIV.hidden;
    cell.nameLabel.text = blu.name;
    cell.delBtn.hidden = cell.batterIV.hidden;
    WeakSelf
    cell.clickDelete = ^{
        [weakSelf.deleteNames addObject:weakSelf.dataArray[indexPath.item].name];
        weakSelf.dataArray[indexPath.item].name = @"";
        weakSelf.dataArray[indexPath.item].uuid = @"";
        [weakSelf.collectionView reloadData];
    };
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.collectItemW, 96);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GroupSearchBleListView *view = (GroupSearchBleListView *)[[[NSBundle mainBundle] loadNibNamed:@"GroupSearchBleListView" owner:self options:nil] firstObject];
    view.frame = [[UIScreen mainScreen] bounds];
    view.count = self.dataArray.count;
    view.tempDeleteName = self.deleteNames;
    NSMutableArray *arr = [NSMutableArray array];
    for (BlutoothModel *m in self.dataArray) {
        if (m.name.length) {
            [arr addObject:m.name];
        }
    }
    view.bleNames = arr;
    WeakSelf
    view.clickDown = ^(NSMutableArray<CBPeripheral *> * _Nonnull list) {
        [weakSelf updateGroup:list];
        [weakSelf.deleteNames removeAllObjects];
    };
    [[UIApplication sharedApplication].delegate.window addSubview:view];
}

- (BOOL)collectionView:(UICollectionView *)collectionView canHandleDropSession:(id<UIDropSession>)session {
    return YES;
}

- (UICollectionViewDropProposal *)collectionView:(UICollectionView *)collectionView dropSessionDidUpdate:(id<UIDropSession>)session withDestinationIndexPath:(NSIndexPath *)destinationIndexPath {
    return [[UICollectionViewDropProposal alloc] initWithDropOperation:UIDropOperationMove intent:UICollectionViewDropIntentInsertIntoDestinationIndexPath];
}

- (NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView itemsForBeginningDragSession:(id<UIDragSession>)session atIndexPath:(NSIndexPath *)indexPath {
    NSString *item = self.dataArray[indexPath.item].uuid;
    NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithObject:item];
    UIDragItem *dragItem = [[UIDragItem alloc] initWithItemProvider:itemProvider];
    dragItem.localObject = item;
    return @[dragItem];
}

- (void)collectionView:(UICollectionView *)collectionView performDropWithCoordinator:(id<UICollectionViewDropCoordinator>)coordinator {
    NSIndexPath *destinationIndexPath = coordinator.destinationIndexPath;
    id<UICollectionViewDropItem> item = coordinator.items.firstObject;
    NSIndexPath *sourceIndexPath = item.sourceIndexPath;
    if (!destinationIndexPath || !sourceIndexPath) return;
    [collectionView performBatchUpdates:^{
        // 交换数据源
        [self.dataArray exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        // 交换 UI
        [collectionView moveItemAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
        [collectionView moveItemAtIndexPath:destinationIndexPath toIndexPath:sourceIndexPath];
    } completion:^(BOOL finished) {
        [collectionView reloadData];
    }];
}

@end
